﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using SLLottery.LotterySrv;
using System.Collections.ObjectModel;
using SLLottery.Common;
using System.Windows.Data;

namespace SLLottery
{
    public partial class GameRecord : UserControl
    {
        public LotterySrv.LotteryServiceClient srv_GameRecord;
        User user = (User)App.Session[Constant.USERINFO_SESSION];
        ObservableCollection<StatReport> obStatReport;
        List<ReportDetail> obReportDetail;
        StatReport RPageSum;
        StatReport RTotalSum;
        ReportDetail DPageSum;
        ReportDetail DTotalSum;
        List<long> BindedLst;
        private int currentPos = 0;
        DateTime startDate
        {
            get { return datePickerStart.SelectedDate.Value.Date; }
            set { datePickerStart.SelectedDate = value; }
        }
        DateTime endDate
        {
            get { return datePickerEnd.SelectedDate.Value.Date.AddDays(1).AddSeconds(-1); }
            set { datePickerEnd.SelectedDate = value; }
        }
        public GameRecord()
        {
            InitializeComponent();
            rbtLists.IsChecked = true;
            datePickerStart.SelectedDate = DateTime.Now;
            datePickerEnd.SelectedDate = DateTime.Now;
            BindedLst = new List<long>();
            RPageSum = new StatReport();
            RPageSum.UserID = "本页合计";
            RTotalSum = new StatReport();
            RTotalSum.UserID = "总合计";
            DPageSum = new ReportDetail();
            DPageSum.RecordID = "本页合计";
            DPageSum.IsWin = -1;
            DPageSum.Direction = -1;
            DPageSum.ResultStatus = -1;
            DTotalSum = new ReportDetail();
            DTotalSum.RecordID = "总合计";
            DTotalSum.IsWin = -1;
            DTotalSum.Direction = -1;
            DTotalSum.ResultStatus = -1;
            srv_GameRecord = WcfProxy.GetProxy;
            srv_GameRecord.GetStatReportCompleted += new EventHandler<GetStatReportCompletedEventArgs>(srv_GameRecord_GetStatReportCompleted);
            srv_GameRecord.GetReportDetailCompleted += new EventHandler<GetReportDetailCompletedEventArgs>(srv_GameRecord_GetReportDetailCompleted);
            TextBlock txtb = new TextBlock()
            {
                Text = "本级",
                Style = Resources["TextBlockStyle1"] as Style,
                Cursor = Cursors.Hand
            };
            txtb.Tag = user.ID;
            BindedLst.Add(user.ID);
            txtb.MouseLeftButtonDown += new MouseButtonEventHandler(txtb_MouseLeftButtonDown);
            NavMenu.Children.Add(txtb);
            BindReportDetailList(user.UserId);
        }
        private void BindStatReportList(Int64 id)
        {
            srv_GameRecord.GetStatReportAsync(id, startDate, endDate);
            gridLoading.Visibility = Visibility.Visible;
        }

        private void BindReportDetailList(string uid)
        {
            srv_GameRecord.GetReportDetailAsync(uid, startDate, endDate);
            gridLoading.Visibility = Visibility.Visible;
        }
        private void srv_GameRecord_GetStatReportCompleted(object sender, GetStatReportCompletedEventArgs e)
        {
            obStatReport = e.Result;
            gridLoading.Visibility = Visibility.Collapsed;
            currentPos = 0;
            if (e.Result.Count != 0)
            {
                RTotalSum = new StatReport();
                RTotalSum.UserID = "总合计";
                RTotalSum.BetMoney = obStatReport.Sum(p => p.BetMoney);
                RTotalSum.WinMoney = obStatReport.Sum(p => p.WinMoney);
                if (e.Result.Count < 18)
                {
                    obStatReport = e.Result;
                    RPageSum = new StatReport();
                    RPageSum.UserID = "本页合计";
                    RPageSum.BetMoney = obStatReport.Take(18).Sum(p => p.BetMoney);
                    RPageSum.WinMoney = obStatReport.Take(18).Sum(p => p.WinMoney);
                    obStatReport.Add(RPageSum);
                    obStatReport.Add(RTotalSum);
                    currentPos = 0;
                    PagedCollectionView pageView = new PagedCollectionView(obStatReport);
                    pageView.PageSize = 20;
                    dpList.PageSize = 20;
                    dpList.Source = pageView;
                    dgList.ItemsSource = pageView;
                }
                else
                {
                    int page = int.Parse(Math.Ceiling(double.Parse(e.Result.Count.ToString()) / 18).ToString());
                    for (int i = 0; i < page; i++)
                    {
                        int stayNum = e.Result.Count - (i * 20);
                        if (stayNum > 18)
                        {
                            RPageSum = new StatReport();
                            RPageSum.UserID = "本页合计";
                            RPageSum.BetMoney = obStatReport.Skip(i * 20).Take(18).Sum(p => p.BetMoney);
                            RPageSum.WinMoney = obStatReport.Skip(i * 20).Take(18).Sum(p => p.WinMoney);
                            obStatReport.Insert(i * 20 + 18, RPageSum);
                            obStatReport.Insert(i * 20 + 19, RTotalSum);
                        }
                        else
                        {
                            RPageSum = new StatReport();
                            RPageSum.UserID = "本页合计";
                            RPageSum.BetMoney = obStatReport.Skip(i * 20).Take(stayNum).Sum(p => p.BetMoney);
                            RPageSum.WinMoney = obStatReport.Skip(i * 20).Take(stayNum).Sum(p => p.WinMoney);
                            obStatReport.Insert(i * 20 + stayNum, RPageSum);
                            obStatReport.Insert(i * 20 + stayNum + 1, RTotalSum);
                        }
                    }
                    currentPos = 0;
                    PagedCollectionView pageView = new PagedCollectionView(obStatReport);
                    pageView.PageSize = 20;
                    dpList.PageSize = 20;
                    dpList.Source = pageView;
                    dgList.ItemsSource = pageView;
                }
            }

        }

        public void srv_GameRecord_GetReportDetailCompleted(object sender, GetReportDetailCompletedEventArgs e)
        {
            gridLoading.Visibility = Visibility.Collapsed;
            currentPos = 0;
            obReportDetail = e.Result.ToList();
            //obReportDetail.Add(DPageSum);
            //obReportDetail.Add(DTotalSum);
            if (e.Result.Count != 0)
            {
                DTotalSum = new ReportDetail();
                DTotalSum.RecordID = "总合计";
                DTotalSum.IsWin = -1;
                DTotalSum.Direction = -1;
                DTotalSum.ResultStatus = -1;
                DTotalSum.BetMoney = obReportDetail.Sum(p => p.BetMoney);
                DTotalSum.WinMoney = obReportDetail.Sum(p => p.WinMoney);
                if (e.Result.Count < 18)
                {
                    obReportDetail = e.Result.ToList();
                    DPageSum = new ReportDetail();
                    DPageSum.RecordID = "本页合计";
                    DPageSum.IsWin = -1;
                    DPageSum.Direction = -1;
                    DPageSum.ResultStatus = -1;
                    DPageSum.BetMoney = obReportDetail.Take(18).Sum(p => p.BetMoney);
                    DPageSum.WinMoney = obReportDetail.Take(18).Sum(p => p.WinMoney);
                    obReportDetail.Add(DPageSum);
                    obReportDetail.Add(DTotalSum);
                    currentPos = 0;
                    PagedCollectionView pageView = new PagedCollectionView(obReportDetail);
                    pageView.PageSize = 20;
                    dpRecord.PageSize = 20;
                    dpRecord.Source = pageView;
                    dgRecord.ItemsSource = pageView;
                }
                else
                {
                    int page = int.Parse(Math.Ceiling(double.Parse(e.Result.Count.ToString()) / 18).ToString());
                    for (int i = 0; i < page; i++)
                    {
                        int stayNum = obReportDetail.Count - (i * 20);
                        if (stayNum > 18)
                        {
                            DPageSum = new ReportDetail();
                            DPageSum.RecordID = "本页合计";
                            DPageSum.IsWin = -1;
                            DPageSum.Direction = -1;
                            DPageSum.ResultStatus = -1;
                            //DPageSum.BetMoney = obReportDetail.Skip(i * 20).Take(18).Sum(p => p.BetMoney);
                            //DPageSum.WinMoney = obReportDetail.Skip(i * 20).Take(18).Sum(p => p.WinMoney);
                            DPageSum.BetMoney = obReportDetail.GetRange(i * 20, 18).Sum(p => p.BetMoney);
                            DPageSum.WinMoney = obReportDetail.GetRange(i * 20, 18).Sum(p => p.WinMoney);
                            obReportDetail.Insert(i * 20 + 18, DPageSum);
                            obReportDetail.Insert(i * 20 + 19, DTotalSum);
                        }
                        else
                        {
                            DPageSum = new ReportDetail();
                            DPageSum.RecordID = "本页合计";
                            DPageSum.IsWin = -1;
                            DPageSum.Direction = -1;
                            DPageSum.ResultStatus = -1;
                            //DPageSum.BetMoney = obReportDetail.Skip(i * 20).Take(stayNum).Sum(p => p.BetMoney);
                            //DPageSum.WinMoney = obReportDetail.Skip(i * 20).Take(stayNum).Sum(p => p.WinMoney);
                            DPageSum.BetMoney = obReportDetail.GetRange(i * 20, stayNum).Sum(p => p.BetMoney);
                            DPageSum.WinMoney = obReportDetail.GetRange(i * 20, stayNum).Sum(p => p.WinMoney);
                            obReportDetail.Insert(i * 20 + stayNum, DPageSum);
                            obReportDetail.Insert(i * 20 + stayNum + 1, DTotalSum);
                        }
                    }
                    currentPos = 0;
                    PagedCollectionView pageView = new PagedCollectionView(obReportDetail);
                    pageView.PageSize = 20;
                    dpRecord.PageSize = 20;
                    dpRecord.Source = pageView;
                    dgRecord.ItemsSource = pageView;
                }
            }
            else
            {
                PagedCollectionView pageView = new PagedCollectionView(obReportDetail);
                pageView.PageSize = 20;
                dpRecord.PageSize = 20;
                dpRecord.Source = pageView;
                dgRecord.ItemsSource = pageView;
            }
            BindStatReportList(user.ID);
        }

        private void txtb_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            TextBlock txtb = sender as TextBlock;
            int index = NavMenu.Children.IndexOf(txtb);
            if (index != NavMenu.Children.Count - 1)
            {
                for (int i = NavMenu.Children.Count - 1; i > index; i--)
                {
                    TextBlock txtblock = NavMenu.Children[i] as TextBlock;
                    if (txtblock.Text != ">")
                        BindedLst.Remove(Int64.Parse(txtblock.Tag.ToString()));
                    NavMenu.Children.RemoveAt(i);
                }
            }
            if (txtb.Text != rbtDetails.Content.ToString())
            {
                rbtLists.IsChecked = true;
                rbtDetails.IsChecked = false;
                BindStatReportList(Int64.Parse(txtb.Tag.ToString()));
            }
            else
            {
                rbtLists.IsChecked = false;
                rbtDetails.IsChecked = true;
                LoadDetail();
            }
        }

        private void rbtLists_Checked(object sender, RoutedEventArgs e)
        {
            gridList.Visibility = Visibility.Visible;
            gridRecord.Visibility = Visibility.Collapsed;
            for (int i = NavMenu.Children.Count - 1; i > 1; i--)
            {
                TextBlock txtblock = NavMenu.Children[i] as TextBlock;
                if (txtblock.Text == rbtDetails.Content.ToString())
                {
                    BindedLst.Remove(Int64.Parse(txtblock.Tag.ToString()));
                    NavMenu.Children.RemoveAt(i);
                    NavMenu.Children.RemoveAt(i - 1);
                    break;
                }
            }
            LoadList();
        }

        private void rbtDetails_Checked(object sender, RoutedEventArgs e)
        {
            gridList.Visibility = Visibility.Collapsed;
            gridRecord.Visibility = Visibility.Visible;

            if (!BindedLst.Contains(-1))
            {
                TextBlock txtb = new TextBlock()
                {
                    Text = ">",
                    Style = Resources["TextBlockStyle2"] as Style,
                };
                NavMenu.Children.Add(txtb);
                txtb = new TextBlock()
                {
                    Text = ((RadioButton)sender).Content.ToString(),
                    Style = Resources["TextBlockStyle0"] as Style,
                };
                txtb.Tag = -1;
                txtb.MouseLeftButtonDown += new MouseButtonEventHandler(txtb_MouseLeftButtonDown);
                NavMenu.Children.Add(txtb);
                BindedLst.Add(-1);
            }
            LoadDetail();

        }

        private void btRefreshRecord_Click(object sender, RoutedEventArgs e)
        {
            BindStatReportList(user.ID);
        }

        private void btSearchList_Click(object sender, RoutedEventArgs e)
        {
            SearchUser searchUser = new SearchUser();
            searchUser.Closed += new EventHandler(SearchUser_Close);  //在父窗体注册子窗体的关闭事件
            searchUser.Show();
        }
        private void SearchUser_Close(object sender, EventArgs e)
        {
            SearchUser searchUser = sender as SearchUser;
            bool? result = searchUser.DialogResult;

            if (result.HasValue && result.Value)
            {
                srv_GameRecord.GetUserInfoAsync(searchUser.userID);
                srv_GameRecord.GetUserInfoCompleted += (s, er) =>
                    {
                        if (er.Result == null)
                            return;
                        if (!BindedLst.Contains(er.Result.ID))
                        {
                            TextBlock txtb = new TextBlock()
                            {
                                Text = ">",
                                Style = Resources["TextBlockStyle2"] as Style,
                            };
                            NavMenu.Children.Add(txtb);
                            txtb = new TextBlock()
                            {
                                Text = er.Result.UserId,
                                Style = Resources["TextBlockStyle0"] as Style,
                            };
                            txtb.Tag = er.Result.ID;
                            txtb.MouseLeftButtonDown += new MouseButtonEventHandler(txtb_MouseLeftButtonDown);
                            NavMenu.Children.Add(txtb);
                            BindedLst.Add(er.Result.ID);
                        }
                        srv_GameRecord.GetStatReportAsync(er.Result.ID, startDate, endDate);
                    };
            }
        }

        private void btRefreshList_Click(object sender, RoutedEventArgs e)
        {
            if (rbtDetails.IsChecked == true)
                LoadDetail();
            else
                LoadList();
        }

        private void dgRecord_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            ReportDetail rd = e.Row.DataContext as ReportDetail;
            if (!string.IsNullOrEmpty(rd.IssueNo))
            {
                (dgRecord.Columns[0].GetCellContent(e.Row) as TextBlock).Text = (dpRecord.PageIndex * (dpRecord.PageSize - 2) + e.Row.GetIndex() + 1).ToString();
            }
            else
                (dgRecord.Columns[0].GetCellContent(e.Row) as TextBlock).Text = "";
            if (Convert.ToDouble(rd.WinMoney) >= 0)
                (dgRecord.Columns[10].GetCellContent(e.Row) as TextBlock).Foreground = new SolidColorBrush(Colors.Red);
            if (rd.RecordID == "本页合计" || rd.RecordID == "总合计")
            {
                (dgRecord.Columns[2].GetCellContent(e.Row) as TextBlock).Visibility = Visibility.Collapsed;
                (dgRecord.Columns[9].GetCellContent(e.Row) as TextBlock).Visibility = Visibility.Collapsed;
            }
            if (rd.ResultStatus == 0)
            {
                rd.WinMoney = 0;
                rd.IsWin = -1;
            }
        }

        private void dgList_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            StatReport sr = e.Row.DataContext as StatReport;
            if (!string.IsNullOrEmpty(sr.RoleName))
            {
                (dgList.Columns[0].GetCellContent(e.Row) as TextBlock).Text = (dpList.PageIndex * (dpList.PageSize - 2) + e.Row.GetIndex() + 1).ToString();
            }
            else
                (dgList.Columns[0].GetCellContent(e.Row) as TextBlock).Text = "";
            if (e.Row.GetIndex() != 0)
            {
                (dgList.Columns[5].GetCellContent(e.Row) as TextBlock).Visibility = Visibility.Collapsed;
            }
            if (sr.RoleName == "会员")
                (dgList.Columns[2].GetCellContent(e.Row) as TextBlock).Foreground = new SolidColorBrush(Common.MyColor.ConvertColor("#ff2ADC16"));
        }

        private void ShowMyUser_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            StatReport info = (sender as TextBlock).DataContext as StatReport;
            if (!BindedLst.Contains(info.ID))
            {
                if (((info != null) && (info.ID != 0)))
                {
                    BindStatReportList(info.ID);
                    BindedLst.Add(info.ID);
                    TextBlock txtb = new TextBlock()
                    {
                        Text = ">",
                        Style = Resources["TextBlockStyle2"] as Style,
                    };
                    NavMenu.Children.Add(txtb);
                    txtb = new TextBlock()
                    {
                        Text = info.UserID,
                        Style = Resources["TextBlockStyle0"] as Style,
                    };
                    txtb.Tag = info.ID;
                    txtb.MouseLeftButtonDown += new MouseButtonEventHandler(txtb_MouseLeftButtonDown);
                    NavMenu.Children.Add(txtb);
                }
            }
        }

        private void ShowOrderDetail_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            TextBlock txtb = sender as TextBlock;
            if (txtb.Text != "本页合计" && txtb.Text != "总合计")
                new DealInfoWindow(Int64.Parse(txtb.Text.Trim())).Show();
        }

        private void ShowDetail_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            rbtDetails.IsChecked = true;
            LoadDetail();
        }

        private void dgRecord_Loaded(object sender, RoutedEventArgs e)
        {
        }
        void LoadDetail()
        {
            for (int i = NavMenu.Children.Count - 1; i >= 0; i--)
            {
                TextBlock tb = NavMenu.Children[i] as TextBlock;
                if (tb.Text == rbtDetails.Content.ToString() || tb.Text == ">")
                    continue;
                if (tb.Text == "本级")
                    BindReportDetailList(user.UserId);
                else
                    BindReportDetailList(tb.Text);
                break;
            }
        }
        void LoadList()
        {
            for (int i = NavMenu.Children.Count - 1; i >= 0; i--)
            {
                TextBlock tb = NavMenu.Children[i] as TextBlock;
                if (tb.Text == rbtDetails.Content.ToString() || tb.Text == ">")
                    continue;
                if (tb.Text == "本级")
                    BindStatReportList(user.ID);
                else
                    BindStatReportList(Convert.ToInt64(tb.Tag));
                break;
            }
        }
        private void btSelect_Click(object sender, RoutedEventArgs e)
        {
            if (rbtDetails.IsChecked == true)
            {
                rbtDetails_Checked(rbtDetails, null);
            }
            else
            {
                rbtLists_Checked(rbtLists, null);
            }
        }

        private void dpRecord_PageIndexChanged(object sender, EventArgs e)
        {
            currentPos = 0;
        }
    }
}
